<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    width="450px"
    @close="handleClose">

    <div>
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="80px" class="demo-ruleForm">

        <el-form-item label="用户名" prop="name">
          <el-input v-model="ruleForm.name" :disabled="IsEad"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="pwd">
          <el-input v-model="ruleForm.pwd"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email" :disabled="IsEad"></el-input>
        </el-form-item>

        <el-form-item label="角色" prop="avatar">
          <el-select v-model="ruleForm.avatar" placeholder="请选择角色" style="width: 100%">
            <el-option label="超级管理员" value="0"></el-option>
            <el-option label="打卡管理员" value="2"></el-option>
            <el-option label="同乐管理员" value="3"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="备注">
          <el-input type="textarea" v-model="ruleForm.user_remarks"></el-input>
        </el-form-item>

      </el-form>

    </div>

    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="OnSubmit('ruleForm')">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script lang="ts">
  import { Component, Emit, Inject, Model, Prop, Provide, Vue, Watch } from 'vue-property-decorator'
  import { addUserReg,regname,regemail, updatauser } from '../../../api/data.js'
  import { anRandom, anTimeGit, angetLocalTime } from '../../../utils/index'
  import {isEmptyValue} from '../../../utils/validate.js'

  interface ObdiaVal {
    name: string;
    pwd:string;
    email:string;
    avatar:string;
    idnumber?:string;
    user_remarks?:string;
  }
  interface ObSQL extends ObdiaVal {
    expire_time?: string;
    id?: number;
    pic?: string;
    reg_date?: string;
    user_token?: string;
  }

  const newNull:ObSQL = {
    name:'',
    pwd:'',
    email:'',
    avatar:'2',
    user_remarks:'',
    idnumber:'',
    expire_time: '',
    id: undefined,
    pic: '',
    reg_date: '',
    user_token: '',
  }


  @Component
  export default class addUser extends Vue {

    validateName = (rule:any, value:string, callback:any) => {
      if(this.IsEad){ //新增
        if (value === '') {
          callback(new Error('用户名不能为空'));
        } else {
          this.IsUserOk(value).then((res:any) =>{
            if(res){
              callback();
            }else{
              callback(new Error('用户名被使用'));
            }
          })
        }
      }else{
        callback();
      }
    };


    dialogVisible:boolean = false;
    title:string = '';
    ruleForm:ObdiaVal={
      name:'', //用户名
      pwd:'',   //密码
      email:'',  //邮箱
      avatar:'0',  //角色
      user_remarks:''  //备注
    };
    IsEad:boolean = false; //是否是修改

    rules:object={
      name:[{ validator: this.validateName, required: true, trigger: 'blur' }],
      pwd:[
          { required: true, message: '不能为空！', trigger: 'blur' },
        ],
      email:[
          {required: true, message: '不能为空！', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
    };

    @Prop()
    dialogObjData:any;

    @Watch('dialogObjData', { immediate: true, deep: true })
    onChildChanged(nd: any, od: any) {
      this.title = nd.til;

      let cd = this.anCopy(nd.RowData);
      if (isEmptyValue(cd)){
        this.IsEad = false;
        this.ruleForm = this.anCopy(newNull);
      }else{
        this.IsEad = true;
        this.ruleForm = cd;
        //console.log(this.ruleForm);
      }
    }

    mounted(){
      this.anLoad();
    }

    anLoad(){


    }
    openDia(){
      this.dialogVisible = true;
    }
    //确定 提交表单
    OnSubmit(formName:any){

      let rel:any = this.$refs[formName];
      rel.validate((valid:boolean) => {
        if (valid) {

          let _this = this;

          if(this.IsEad){ //修改

            let nd:ObdiaVal = _this.ruleForm;
            //console.log(nd);
            _this.dialogVisible = false;
            updatauser(nd).then( (res:any) =>{
              if(res.data.isok === '1'){
                _this.$message.success('修改成功');
                this.$emit('childByValue', 1)
              }else{
                _this.$message.error(res.msg);
              }
            })

          }else{ //新增

            let anFunc = function () {
              let nd:ObdiaVal = _this.ruleForm;
              nd.idnumber = anTimeGit().toString();
              //console.log(nd);
              _this.dialogVisible = false;
              addUserReg(nd).then( (res:any) =>{
                if(res.data.isok === '1'){
                  _this.$message.success('添加成功');
                  _this.$emit('childByValue', 1)
                }else{
                  _this.$message.error(res.msg);
                }
              })
            };

            this.IsEmailOk(this.ruleForm.email).then((res:boolean)=>{
              if(res){
                anFunc();
              }else{
                this.$message.error('邮箱已被使用');
              }
            })

          }

        }
      });
    };
    //验证用户名是否重复  async/await ES6新语法
    async IsUserOk(val:string){
      //查询数据库用户名是否重复
      let nd:boolean = false;
      await regname(val).then((res:any)=>{
          if(res.data.isok==='0'){
            nd = true;
          }
      });
      return nd;
    };
    //验证邮箱是否重复
    IsEmailOk(val:string):any{
      return regemail(val).then((res:any)=>{
        let nd:boolean = false;
        if(res.data.isok==='0'){
          nd = true;
        }
        return nd
      })
    }

    //关闭执行
    handleClose(){
      this.clearForm();
    };
    //重置表单
    clearForm(){
      let el:any = this.$refs['ruleForm'];
      el.resetFields();
    };

    anCopy(obj:any):any{
      let newobj:any = {};
      for ( let attr in obj) {
        newobj[attr] = obj[attr];
      }
      return newobj;
    }

  }
</script>

<style scoped>

</style>
